import json
import re

from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from .models import User, Address
import logging
logger = logging.getLogger('django')

from django.http import HttpResponse, JsonResponse
from django.contrib.auth import login,authenticate
# 导入:
from django.contrib.auth import logout
from meiduo_mall.utils.views import LoginRequiredJSONMixin


class UserBrowseHisteryView(View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 校验参数:
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'sku不存在'})

        user_id = request.user.id

        redis_conn = get_redis_connection('histery')

        pl = redis_conn.pipeline()
        pl.lrem('histery_%s' % user_id, 0, sku_id)
        pl.lpush('histery_%s' % user_id, sku_id)
        pl.ltrim('histery_%s' % user_id, 0, 4)
        pl.execute()

        return JsonResponse({'code': 0, 'errmsg': 'OK'})


    def get(self, request):

        user_id = request.user.id

        redis_conn = get_redis_connection('histery')
        sku_ids = redis_conn.lrange('histery_%s' % user_id, 0, -1)

        skus = []

        for sku_id in sku_ids:
            try:
                sku = SKU.objects.get(id=sku_id)
            except Exception as e:
                return JsonResponse({'code': 200, 'errmsg': 'sku不存在'})
            skus.append({
                "id": sku.id,
                "name": sku.name,
                "default_image_url": sku.default_image.url,
                "price": sku.price
            })

        return JsonResponse({
            "code":"0",
            "errmsg":"OK",
            "skus":skus
        })





class UpdateAddressTitleView(View):

    def put(self, request, address_id):

        json_dict = json.loads(request.body.decode())

        title = json_dict.get('title')

        try:
            Address.objects.filter(id=address_id).update(title=title)
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': '数据库读写失败'})
        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class DefaultAddressView(View):

    def put(self, request, address_id):

        try:
            request.user.default_address_id = address_id
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': '数据库读写失败'})
        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class UpdateAddressView(View):

    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())

        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([address_id, receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 200, 'errmsg': 'mobile格式有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': 'email参数格式有误'})

        try:
            address = Address.objects.filter(id=address_id)

            address.update(
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '数据库写入失败'})

        try:
            address = Address.objects.get(id=address_id)
            address_dict = {
                'id': address_id,
                'receiver': address.receiver,
                'province':address.province.name,
                'city':address.city.name,
                'district':address.district.name,
                'place':address.place,
                'mobile':address.mobile,
                'tel':address.tel,
                'email':address.email
            }
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '数据库错误'})

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def delete(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': '删除失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok'})



class ShowAddressView(View):

    def get(self, request):
        try:
            user = request.user
            addresses = Address.objects.filter(user=user,is_deleted=False)

            addresses_list = []

            for address in addresses:
                address_dict = {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                }

                if address.id == user.default_address_id:
                    addresses_list.insert(0 ,address_dict)
                else:
                    addresses_list.append(address_dict)

        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': '数据库读写失败'})

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'default_address_id': user.default_address_id,
            'addresses': addresses_list,
            'limit': 20
        })


class CreateAddressView(View):

    def post(self, request):

        try:
            count = request.user.addresses.all().count()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 200, 'errmsg': '数据库读写失败'})

        if count >= 20:
            return JsonResponse({'code': 200, 'errmsg': '地址数量超过上限'})

        json_dict = json.loads(request.body.decode())

        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 200, 'errmsg': 'mobile格式有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 200, 'errmsg': 'email参数格式有误'})

        try:
            new_address = Address(
                user=request.user,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                title = receiver,
                receiver = receiver,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
            new_address.save()

            if request.user.default_address is None:
                request.user.default_address = new_address
                request.user.save()
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': '数据库写入失败'})



        address_dict = {
            "id": new_address.id,
            "title": new_address.title,
            "receiver": new_address.receiver,
            "province": new_address.province.name,
            "city": new_address.city.name,
            "district": new_address.district.name,
            "place": new_address.place,
            "mobile": new_address.mobile,
            "tel": new_address.tel,
            "email": new_address.email
        }

        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})


class UpdatePasswordView(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())

        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not request:
            return JsonResponse({"code": 200, 'errmsg': '原始密码错误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,
                                 'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({"code": 200, 'errmsg': '两次密码输入不一致'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 200, 'errmsg': '数据库保存失败'})

        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        return response


class VerifyEmailView(View):
    """验证邮箱"""

    def put(self, request):
        """实现邮箱验证逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数：判断 token 是否为空和过期，提取 user
        if not token:
            return  JsonResponse({'code':400,
                                  'errmsg':'缺少token'})

        # 调用上面封装好的方法, 将 token 传入
        user = User.check_verify_email_token(token)
        if not user:
            return  JsonResponse({'code':400,
                                  'errmsg':'无效的token'})

        # 修改 email_active 的值为 True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'激活邮件失败'})

        # 返回邮箱验证结果
        return JsonResponse({'code':0,
                             'errmsg':'ok'})


class CreateEmailView(View):

    def put(self, request):
        json_dict = json.loads(request.body.decode())

        email = json_dict.get('email')

        if not email:
            return JsonResponse({'code': 200, 'errmsg': '缺少email参数'})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 200, 'errmsg': 'email参数格式有误'})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 200, 'errmsg': '数据库保存失败'})

        email = '<' + email + '>'
        # 从 celery_tasks 中导入:
        from celery_tasks.email.tasks import send_verify_email
        # 调用发送的函数:
        verify_url = request.user.generate_verify_email_url()
        send_verify_email.delay(email, verify_url)

        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class LoginView(View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())
        account = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')


        if not all([account, password]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '参数password格式有误'})

        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        try:
            user = authenticate(request, username=account, password=password)
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': '数据库读取错误'})

        if user == None:
            return JsonResponse({'code': 200, 'errmsg': '用户名或密码错误'})

        login(request, user)
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})

        if remembered == True:
            request.session.set_expiry(None)
            response.set_cookie('username',
                                user.username,
                                max_age=3600 * 24 * 14)
        else:
            request.session.set_expiry(0)
            response.set_cookie('username',
                                user.username)

        # 生成响应对象


        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天


        # 返回响应结果
        return response


class LogoutView(View):
    """定义退出登录的接口"""

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'code':0,
                                 'errmsg':'ok'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response


class UsernameCountView(View):
    '''用户名查重接口'''
    def get(self, request, username):

        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '数据库读取错误'})

        return JsonResponse({'code': 0, 'errmsg': 'ok', "count": count})


class MobileCountView(View):
    """用户手机号重复注册接口"""
    def get(self, request, mobile):

        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '数据库读取错误'})

        return JsonResponse({'code': 0, 'errmsg': 'ok', "count": count})


class RegisterView(View):
    """用户注册接口"""
    def post(self, request):

        json_dict = json.loads(request.body.decode())

        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 200, 'errmsg': 'username格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 200, 'errmsg': 'password格式有误'})

        if password != password2:
            return JsonResponse({'code': 200, 'errmsg': '两次输入password不一致'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 200, 'errmsg': 'mobile格式有误'})

        if allow != True:
            return JsonResponse({'code': 200, 'errmsg': 'allow格式有误'})

        redis_conn = get_redis_connection("verify")
        sms_code_server = redis_conn.get('sms_code_%s' % mobile)

        if not sms_code_server:
            return JsonResponse({'code': 200, 'errmsg': '短信验证码已过期'})

        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 200, 'errmsg': '短信验证码错误'})

        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile,
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 200, 'errmsg': '数据库写入失败'})

        login(request, user)

        # 生成响应对象
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        # response.set_cookie('username',
        #                     user.username,
        #                     max_age=3600 * 24 * 14)

        # 返回响应结果
        return response


class UserInfoView(LoginRequiredJSONMixin, View):

    def get(self, request):

        user = request.user

        data_dict = {
            'code': 0,
            'errmsg': 'ok',
            'info_data': {
                'username': user.username,
                'mobile': user.mobile,
                'email': user.email,
                'email_active': user.email_active
            }
        }
        return JsonResponse(data_dict)



